import React from 'react';
// 引入编辑器组件
import BraftEditor from 'braft-editor';
import { ContentUtils } from 'braft-utils';
// 引入编辑器样式
import 'braft-editor/dist/index.css';
import CUploadView from '@/components/common/CUpload/CUploadView';
import { Button, message } from 'antd';
import styles from './index.less';
import { setContent } from '@/services/admin/common/api';
interface TypeProps {
  value: any;
  height?: number;
  onChange: any;
  placeholder?: string;
}
let modalVisibleImageViewModal: CUploadView | null = null;
class CBraftEditor extends React.Component<any, TypeProps> {
  constructor(props: TypeProps) {
    super(props);
    this.state = {
      value: BraftEditor.createEditorState(props.value || '<p></p>'),
      height: props.height || 300,
      onChange: props.onChange,
      placeholder: props.placeholder || '请输入...',
    };
  }
  handleEditorChange = (value: any) => {
    this.setState({ value });
    this.state.onChange(value.toHTML());
  };
  extendControlsContent: any = [
    {
      key: 'antd-uploader',
      type: 'component',
      component: (
        <>
          <CUploadView
            ref={(com) => {
              modalVisibleImageViewModal = com;
            }}
            key={9}
            count={9}
            onChange={async (data: any) => {
              console.log(data);
              if (data.length) {
                const arr = [];
                for (let i = 0; i < data.length; i++) {
                  arr.push({ type: 'IMAGE', url: data[i].http_url });
                }
                this.setState({
                  value: ContentUtils.insertMedias(this.state.value, arr),
                });
              }
            }}
          />
          <Button
            type="primary"
            size="small"
            className={styles.uploadBtn}
            onClick={() => {
              modalVisibleImageViewModal?.show();
            }}
          >
            上传图片
          </Button>
        </>
      ),
    },
  ];
  submitContent = async () => {
    const hide = message.loading('解析中..', 0);
    const htmlContent = this.state.value.toHTML();
    const res = await setContent(htmlContent);
    if (res.status === 20000) {
      this.setState({ value: BraftEditor.createEditorState(res.data.content) });
      this.state.onChange(BraftEditor.createEditorState(res.data.content));
      hide();
      message.success(res.message);
    }
  };
  render() {
    const { value, height } = this.state;
    return (
      <div className={styles.component}>
        <BraftEditor
          value={value}
          excludeControls={['media']}
          contentStyle={{ height: height }}
          onChange={this.handleEditorChange}
          placeholder={this.state.placeholder}
          extendControls={this.extendControlsContent}
          onSave={this.submitContent}
        />
        <span className={styles.msg}>在编辑器内按下Command/Ctrl + s时可以保存远程图片</span>
      </div>
    );
  }
}
export default CBraftEditor;
